﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Procurios.Public;

public partial class ChatPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Request.SaveAs(@"C:\Users\Logan Su\Desktop\HttpRequest.txt", true);
        DateTime start = DateTime.Now;
        //grab input
        System.IO.StreamReader reader = new System.IO.StreamReader(Request.InputStream);
        string contents = reader.ReadToEnd();
        object response = ProcessContents(JSON.JsonDecode(contents));

        //create response
        Response.AddHeader("Content-Type", "application/json");
        Response.AddHeader("Cache-Control", "no-cache");
        Response.Charset = "UTF-8";
        DateTime end = DateTime.Now;
        TimeSpan span = end - start;
        ((response as ArrayList)[0] as Hashtable).Add("time", span.TotalSeconds);
        Response.Write(JSON.JsonEncode(response));
    }
    //message types
    private static string MSG_TYP_CHAT = "chat";
    private static string MSG_TYP_STATUS = "status";
    private static string MSG_TYP_MSG = "msg";
    private static string MSG_TYP_GETMSG = "getmsg";
 
    private object ProcessContents(object obj)
    {
        ArrayList response = new ArrayList();
        ArrayList request = obj as ArrayList;
        try
        {
            if (request != null)
            {
                foreach (object req in request)
                {
                    Hashtable table = req as Hashtable;
                    if (table == null)
                        break;
                    if (!table.ContainsKey("type"))
                        throw new Exception("no type property");
                    string msgtype = (string)table["type"];
                    if (msgtype == MSG_TYP_CHAT)
                        ;
                    else if (msgtype == MSG_TYP_STATUS)
                        ;
                    else
                        throw new Exception("illegal msgtype");
                }
                throw new Exception("processing complete");
            }
            else
                throw new Exception("bad request");
        }
        catch (Exception e)
        {
            Hashtable prop = new Hashtable();
            prop.Add("type", "error");
            prop.Add("error", e.Message);
            response.Add(prop);
        }
        return response;
    }
}
